package com.cl.oauth.service.service;

import com.cl.oauth.core.common.model.vo.SecurityUser;
import com.cl.oauth.service.mapper.SysUserMapper;
import com.cl.oauth.service.model.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 *
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.getByLoginName(userName);
        if(null == user) {
            // 如果为空，证明用户不存在
            throw new UsernameNotFoundException("用户不存在");
        }

        // 查询拥有的所有权限
        Set<GrantedAuthority> authorities = new HashSet<>();
        Map<String, Object> params = new HashMap<>(2);
        params.put("id", user.getId());
        params.put("sysMark", user.getSysMark());

        Set<String> userPermission = sysUserMapper.getUserPermission(params);
        userPermission.forEach(item -> {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(item);
            authorities.add(grantedAuthority);
        });

        return SecurityUser.builder()
                .username(user.getUserName())
                .password(user.getPassword())
                .authorities(authorities)
                .enabled(!user.getEnable())
                .build();
    }
}
